package 数组;

public class 最小子数组 {
    public static void main(String[] args) {

        int res = minSubArrayLen(11, new int[]{1,1,1,1,1,1,1,1});
    }
    public static int minSubArrayLen(int target, int[] nums){
        int res = Integer.MAX_VALUE;
        int sub = 0;
        int i = 0;
        int sum = 0;
        for(int j = 0; j < nums.length; j++){
            sum += nums[j];
            while(sum >= target){
                sub = j - i + 1;
                res = res < sub? res : sub;
                sum -= nums[i++];

            }
        }
        return res == Integer.MAX_VALUE? 0 : res;

    }

    // 暴力超时
    public static int minSubArrayLen2(int target, int[] nums) {
        int res = Integer.MAX_VALUE;
        int sub = 0;
        for(int i = 0; i < nums.length; i++){
            int sum = 0;
            sub = 0;
            for(int j = i; j < nums.length; j++){
                sum += nums[j];
                sub ++;
                if(sum >= target){
                    res = res < sub? res : sub;
                    break;
                }
            }
        }
        return res == Integer.MAX_VALUE? 0 : res;
    }

}
